// 
//  prefs.js
//  firefox
//  
//  Created by Zak on 2008-06-17.
//  Copyright 2008 Ant.com. All rights reserved.
// 

top.AntPrefs = 
{
	init: function ()
	{
		var flvDir;

		if (!this.flvDir())//first run
		{
			flvDir = CCSV("@mozilla.org/file/directory_service;1", "nsIProperties").get("ProfD", CI("nsIFile"));
			var appDir = CCSV("@mozilla.org/file/directory_service;1", "nsIProperties").get("ProfD", CI("nsIFile"));

			flvDir.append("antbar");
			this.flvDir(flvDir.path);
                        //set the default search Engine to Ant.com

                        var branch = CCSV("@mozilla.org/preferences-service;1", "nsIPrefService").getBranch("browser.search.");
                        branch.setCharPref("defaultenginename", "Ant.com");
		}
		else
		{
			flvDir = CCIN("@mozilla.org/file/local;1", "nsILocalFile");
			flvDir.initWithPath(this.flvDir());
		}
		if (!flvDir.exists())
			flvDir.create(CI("nsIFile").DIRECTORY_TYPE, 0777);

		this.setAntUserAgent();
		this.attachObserver();
		this.flashTrusting();
	},

    /**
     * Display a FilePicker to chose the Video directory
     */
    selectFlvDir: function ()
    {
        const nsIFilePicker = CI("nsIFilePicker");
        var fp = CCIN("@mozilla.org/filepicker;1", "nsIFilePicker");
		var path = $("AntPrefsFlvDir").value;

		if (path)
		{
			var file = CCIN("@mozilla.org/file/local;1", "nsILocalFile");

			file.initWithPath(path);
			fp.displayDirectory = file;
		}
        fp.init(window, AntLang.getString("AntPrefs.selectFlvDirTxt"), CI("nsIFilePicker").modeGetFolder);
        
        var res = fp.show();
        
        if (res == nsIFilePicker.returnOK) 
        {
            path = fp.file.path;
            $("AntPrefsFlvDir").value = path;
            this.flvDir(path);
        }
    },


	/**
	 * AttachObsever
	 */
	attachObserver: function ()
	{
		var observer = {observe: function () 
			{
				AntFlvUi.hideMovieListButton(!AntPrefs.isExpertMode()); 

		        var branch = CCSV("@mozilla.org/preferences-service;1", "nsIPrefService")
			        .getBranch("network.http.");
				branch.setBoolPref("use-cache", !AntPrefs.isExpertMode());
			}};
	    var branch = this.getAntBranch();

		branch.QueryInterface(Components.interfaces.nsIPrefBranch2);
		branch.addObserver("", observer, false);
	},

	/**
	 * If the user Agent does not contain Ant.com we add it
	 */
	setAntUserAgent: function ()
	{
		var branch = CCSV("@mozilla.org/preferences-service;1", "nsIPrefService")
				.getBranch("general.useragent.extra.");

		if (branch.getCharPref("firefox").indexOf("Ant.com") == -1)
			branch.setCharPref("firefox", branch.getCharPref("firefox") + ", Ant.com");
	},
	
	
	/**
	 * Return the array of site where we want to enable the downloader
	 * @return sitesArray       array of sites identified by strings
	 */
	getSitesList: function ()
	{
		var enabledDomains = this.enabledDomains();
		var list = new AntArray();

		if (!enabledDomains)
			return list;
		list.fromArray(enabledDomains.split(","));
	    return list;
	},

	/**
	 *	Return the domain from an url
	 */
	getDomain: function (url)
	{
		url += "";
		if (!url)
			return false;
		var match = url.match(/^https?:\/\/(?:[\w]+\.)*([\w-]+\.[\w-]+)/);

		if (!match || match.length < 2)
			return false;
		return match[1];
	},
	
	/**
	 * Remove the given site from the list
	 * @param url               The url of the website to remove
	 */
	removeSite: function (url)
	{
		var domain = this.getDomain(url);
		var ed = this.getSitesList();

		ed.removeValue(domain);
		this.enabledDomains(ed.join(","));
	},

	/**
	 * Remove the given domain from the list
	 * @param url               The url of the website to remove
	 */
	removeDomain: function (domain)
	{
		var ed = this.getSitesList();

		ed.removeValue(domain);
		this.enabledDomains(ed.join(","));
	},
	
	/**
	 * Add the given site to the list
	 * @param url               The url of the website to add
	 */
	addSite: function (url)
	{
		var domain = this.getDomain(url);

		if (domain)
		{
			var ed = this.getSitesList();

			ed.push(domain.toLowerCase());
			ed = ed.uniq();
			this.enabledDomains(ed.join(","));
		}
	},
	
	/**
	 * return true or false if the url is ok to enable
	 * @param url any url
	 */
	isSiteEnabled: function (url)
	{
		var domain = this.getDomain(url);
		var pref = this.enabledDomains();
		var enabledDomains = new AntArray();

		if (!pref)
			return false;
		enabledDomains.fromArray(pref.split(","));
		return enabledDomains.inArray(domain);
	},
	
    /**
     * return the Ant pref branch
     */
    getAntBranch: function ()
    {
        return CCSV("@mozilla.org/preferences-service;1", "nsIPrefService")
                .getBranch("extensions.anttoolbar.");
    },
    
    /**
	 * make Flash trust our flv player 
	 */
	flashTrusting: function ()
	{
		var home = CCSV("@mozilla.org/file/directory_service;1", "nsIProperties").get("Home", CI("nsIFile"));
		var foStream = CCIN("@mozilla.org/network/file-output-stream;1", "nsIFileOutputStream");
		var data = "chrome://antbar/content/player/\n";
		var os = AntLib.getOsName();
	
		switch (os)
		{
			case "Linux":
				home = this.mkchdir(home, ".macromedia");
				if (!home)
					return ;
				home = this.mkchdir(home, "Flash_Player");
			break;

			case "WINNT":
				if (!this.mkchdir(home, "Application Data"))
					return;	
				if (!this.mkchdir(home, "Macromedia"))
					return ;
				if (!this.mkchdir(home, "Flash Player"))
					return ;
			break;

			case "Darwin":
				if (!this.mkchdir(home, "Library"))
					return ;
				if (!this.mkchdir(home, "Preferences"))
					return ;
				if (!this.mkchdir(home, "Macromedia"))
					return ;
				if (!this.mkchdir(home, "Flash Player"))
					return ;

			break;
			default:
				AntLib.toLog("os Not found in AntPrefs");
		}

		if (!home)
			return ;
		home = this.mkchdir(home, "#Security");
		if (!home)
			return ;
	
		home = this.mkchdir(home, "FlashPlayerTrust");
		home.append("antbar.cfg");
		if (home.exists())
			return ;
		home.create(CI("nsIFile").NORMAL_FILE_TYPE, 0777);
	
		foStream.init(home, 0x02 | 0x08 | 0x20, 0666, 0); // write, create, truncate
		foStream.write(data, data.length);
		foStream.close();
	},
	
	/**
	 * Create the directory if it does not exist  and change dir
	 */
	mkchdir: function (dir, to)	
	{
		dir.append(to);
		if (!dir.exists())
		{
			try
			{
				dir.create(CI("nsIFile").DIRECTORY_TYPE, 0777);
			}
			catch (e)
			{
				AntLib.toLog("AntPrefs.mkchdir ERROR = " + e);
				return false;
			}
		}
		if (!dir.isDirectory())
		{
			return false;
		}
		return dir;
	},

    /**
     * Geters/Seters for extension preferences
     */
    isExpertMode: function (/* value */)
    {
        if (arguments.length > 0)
            this.getAntBranch().setBoolPref("expertmode", arguments[0]);
        return this.getAntBranch().getBoolPref("expertmode");
    },
    
    enabledDomains: function (/* value */)
    {
        if (arguments.length > 0)
            this.getAntBranch().setCharPref("enabledDomains", arguments[0]);
        return this.getAntBranch().getCharPref("enabledDomains");
    },
    
    flvDir: function (/* value */)
    {
        if (arguments.length > 0)
            this.getAntBranch().setCharPref("flvdir", arguments[0]);
        return this.getAntBranch().getCharPref("flvdir");
    },
    
    flvToPlay: function (/* value */)
    {
        if (arguments.length > 0)
            this.getAntBranch().setCharPref("flvToPlay", arguments[0]);
        return this.getAntBranch().getCharPref("flvToPlay");
    },

}
